#include "LogManager.h"

LogManager logManager;

LogManager::LogManager(void)
{
    char szModuleName[MAX_PATH];
    char szDrive[3];
    char szDir[MAX_PATH];
    char szLogPath[MAX_PATH];
    GetModuleFileName(NULL, szModuleName, MAX_PATH);
    _splitpath(szModuleName, szDrive, szDir, NULL, NULL);
    strcpy(szLogPath, szDrive);
    strcat(szLogPath, szDir);
    strcat(szLogPath, "application.log");

    szLogFilePath = szLogPath;
    ulLogFileMaxSize = 1*1024*1024;

    InitializeCriticalSection(&criticalSection);
}

LogManager::~LogManager(void)
{
    DeleteCriticalSection(&criticalSection);
}

void LogManager::SetLogFilePath(const std::string& szNewPath)
{
    szLogFilePath = szNewPath;
}

const std::string LogManager::GetLogFilePath()
{
    return szLogFilePath;
}

void LogManager::SetLogFileMaxSize(const unsigned long& ulNewSize)
{
    ulLogFileMaxSize = ulNewSize;
}

const unsigned long LogManager::GetLogFileMaxSize()
{
    return ulLogFileMaxSize;
}

void LogManager::PutWithDateAndTime(char* text, ...)
{
    EnterCriticalSection(&criticalSection);
    if (ulLogFileMaxSize > 0)
    {
        CheckLogSize();

        va_list argp;
        va_start(argp, text);

        time_t t = time(NULL);
        tm timeTM = *localtime(&t);

        FILE* f = fopen(szLogFilePath.c_str(), "a");
        if (f)
        {
            fprintf(f, "%02u-%02u-%04u %02u:%02u:%02u - %u - ", timeTM.tm_mday, timeTM.tm_mon+1, timeTM.tm_year+1900, timeTM.tm_hour, timeTM.tm_min, timeTM.tm_sec, GetCurrentThreadId());
            vfprintf(f, text, argp);
            fclose(f);
        }
    }
    LeaveCriticalSection(&criticalSection);
}

void LogManager::CheckLogSize()
{
    int hFile;

    if( (hFile = open(szLogFilePath.c_str(), _O_RDWR, _S_IREAD | _S_IWRITE))  != -1)
    {
        unsigned long lFileSize = (unsigned long)filelength(hFile);
        close(hFile);
        if (lFileSize >= ulLogFileMaxSize)
        {
            unlink(szLogFilePath.c_str());
        }
    }
}
